/**
 * Created by 王健 on 2018/2/21.
 */

function clear_map() {
    delete window.map;

}

function b_init(lat, lng, zoom) {
    var defer = $.Deferred();

    setTimeout(function () {
        window.map = new BMap.Map("allmap");
        // 创建Map实例
        // if(address){
        //     map.centerAndZoom(address,8);  // 初始化地图,设置中心点坐标和地图级别
        // }else{
        //     map.centerAndZoom("上海",5);  // 初始化地图,设置中心点坐标和地图级别
        // }

        if (!lat) {
            lat = 24.271025738399786;
        }
        if (!lng) {
            lng = 108.17826741000363;
        }
        if (!zoom) {
            zoom = 6;
        }

        window.map.centerAndZoom(new BMap.Point(lng, lat), zoom);

        //添加地图类型控件
        map.addControl(new BMap.MapTypeControl({
            mapTypes:[
                BMAP_HYBRID_MAP
            ]}));
        // map.setCurrentCity("上海");          // 设置地图显示的城市 此项是必须设置的
        window.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        defer.resolve();
    },500)


    return defer.promise();
}

function get_map_center() {
    var point = map.getCenter();
    var obj = {'la': point.lat, 'ln': point.lng};
    obj['lat'] = function () {
        return point.lat;
    }
    obj['lng'] = function () {
        return point.lng;
    }
    return obj
}

function get_map_zoom() {
    return map.getZoom()
}

function b_current_position() {
    var defer = $.Deferred();
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            // var mk = new BMap.Marker(r.point);
            // map.addOverlay(mk);
            // map.panTo(r.point);
            // alert('您的位置：'+r.point.lng+','+r.point.lat);
            defer.resolve(r.point);

        } else {
            // alert('failed'+this.getStatus());
        }
    }, {enableHighAccuracy: true})

    return defer.promise();
}

function GetDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
}